<template>
	<view v-if="goodsList.length > 0">
		<view class="goodsItem" @click="gotoDetails(item.goods_id)" v-for="(item,i) in goodsList" :key="i">
			<view class="divImg">
				<image style="width:100%;" :src="item.goods_small_logo" mode="widthFix"></image>
			</view>
			<view class="divInfo">
				<view class="infoName">
					{{item.goods_name}}
				</view>
				<view class="price">
					￥{{fixedTo(item.goods_price)}}
				</view>
			</view>
		</view>
	</view>
	<view style="text-align:center;margin-top: 100px;" v-else>
		{{message}}
	</view>
</template>

<script>
	export default {
		data() {
			return {
				queryData:{
					query:"",
					cid:"",
					pagenum:1,
					pagesize:10
				},
				goodsList:[],
				message:'',
				total:0,
				flag:true
			};
		},
		onLoad(options){
			// 将页面参数转存到 this.queryData 对象中
			this.queryData.query = options.query || '';
			this.queryData.cid = options.cid || '';
			this.loadGoodList()
		},
		//上拉分页加载
		onReachBottom(){
			if(this.total > this.goodsList.length){
				this.loadGoodList()
			}
		},
		//下拉刷新
		onPullDownRefresh(){
			this.queryData.pagenum = 1;
			this.goodsList = [];
			this.total = 0;
			this.flag = true;
			this.message = "";
			this.loadGoodList();
		},
		methods:{
			loadGoodList(){
				//节流
				if(this.flag != true){
					return
				}
				this.flag = false;
				uni.$http.get('/api/public/v1/goods/search', this.queryData).then((res)=>{
					console.log(res);
					setTimeout(()=>{
						this.goodsList = [...this.goodsList,...res.data.message.goods];
						this.total = res.data.message.total;
						this.queryData.pagenum++;//上拉加载页面++
						uni.stopPullDownRefresh();//结束下拉刷新
						if(this.goodsList.length == 0){//没有数据时
							this.message = "暂时没有商品！"
						}
						this.flag = true;
					},1000)//模拟网络加载速度慢，会出现数据重复的现象
				})
			},
			// 把数字处理为带两位小数点的数字
			fixedTo(i){
				return i.toFixed(2)
			},
			gotoDetails(id){
				uni.navigateTo({
					url:"/subpkg/goods_detail/goods_detail?goods_id=" + id
				})
			},
		}
	}
</script>

<style lang="scss">
	.goodsItem{
		display:flex;
		padding:20rpx;
	}
	.divImg{
		width:160rpx;
		height:160rpx;
		overflow:hidden;
		margin-right:20rpx;
	}
	.divInfo{
		flex:1;
		display:flex;
		flex-direction:column;
		justify-content:space-between;
	}
	.price{
		color:red;
		font-size:24px;
		font-weight:bold;
	}
</style>
